package handle.data;

import save.data.User;
import utils.DataBaseUtil;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet(name = "edit", value = "/edit")
public class edit extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        User loginBean = (User)request.getSession(true).getAttribute("loginBean");

        Connection con = null;
        PreparedStatement preparedStatement=null;
        if (title==""||content==""){
            RequestDispatcher dispatcher=
                    request.getRequestDispatcher("edit.jsp");
            dispatcher.forward(request, response);//转发
        }
        try {

            con = DataBaseUtil.getConnection();

            //获取用户的userId

            int userId = loginBean.getUserId();
            String nowTime = new SimpleDateFormat("YYYY-MM-dd").format(new Date());

            String insertCondition = "INSERT INTO blog_content(title,content,createTime,userId,publisher) VALUES (?,?,?,?,?)";
            preparedStatement = con.prepareStatement(insertCondition);
            preparedStatement.setString(1, title);
            preparedStatement.setString(2, content);
            preparedStatement.setDate(3, java.sql.Date.valueOf(nowTime));
            preparedStatement.setInt(4, userId);
            preparedStatement.setString(5,loginBean.getUsername());
            preparedStatement.execute();

            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index");
            requestDispatcher.forward(request,response);
        }
        catch (Exception e){
            System.out.println("发布博客的错误 = " + e);
        }
        finally {
            DataBaseUtil.close(null,null,con,preparedStatement);
        }

    }
}
